package com.googlecode.agscrum.model.validator;

import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.googlecode.agscrum.model.exceptions.GScrumDomainException;
import com.googlecode.agscrum.model.exceptions.GScrumMessageException;
import com.googlecode.agscrum.model.exceptions.MessageFactory;
import com.googlecode.agscrum.model.exceptions.GScrumDomainException.TypeMessage;

@Component("validatorUtil")
@Scope(value = "singleton")
public class ValidatorUtil {
	@Autowired
	private MessageFactory messageFactory;

	public void setMessageFactory(MessageFactory messageFactory) {
		this.messageFactory = messageFactory;
	}

	@SuppressWarnings("unchecked")
	public void validate(Object object) throws GScrumDomainException {
		ClassValidator classValidator = new ClassValidator(object.getClass());
		InvalidValue[] invalidmessages = classValidator
				.getInvalidValues(object);
		GScrumDomainException gScrumDomainException = new GScrumDomainException();
		for (InvalidValue invalidValue : invalidmessages) {
			GScrumMessageException gScrumMessageException = messageFactory
					.createMessage(invalidValue.getMessage(), invalidValue
							.getMessage(), TypeMessage.ERROR);
			gScrumDomainException.addMessage(gScrumMessageException);
		}
		if (invalidmessages.length > 0) {
			throw gScrumDomainException;
		}
	}
}
